from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.core.validators import RegexValidator
from django.db import models

from article.models import Article
from utils import constants


class UserManager(BaseUserManager):
    def create_user(self, username, password, phone_number=None, email=None):
        user = self.model(
            username=username,
            phone_number=phone_number,
            email=email
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, password, phone_number=None, email=None):
        user = self.create_user(username, password, phone_number, email)
        user.is_admin = True
        user.save(using=self._db)
        return user


class User(AbstractBaseUser):
    id = models.AutoField(primary_key=True, verbose_name='用户ID')
    username = models.CharField(unique=True, max_length=12, verbose_name='用户名')
    password = models.CharField(max_length=128, verbose_name='密码')
    last_login = models.DateTimeField(blank=True, null=True, verbose_name='上次登陆时间')
    is_admin = models.BooleanField(default=False, verbose_name='是否是管理员')
    email = models.EmailField(max_length=255, unique=True, null=True, verbose_name='邮箱')
    phone_number = models.CharField(max_length=11, unique=True, null=True,
                                    validators=[RegexValidator(regex=r'^1[3-9]\d{9}$', message='手机号码格式错误')],
                                    verbose_name='手机号码')
    identity = models.SmallIntegerField(default=constants.IDENTITY_USER,
                                        choices=constants.USER_IDENTITY,
                                        verbose_name='用户身份')
    create_date = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    last_change_date = models.DateTimeField(auto_now=True, verbose_name='修改时间')

    objects = UserManager()

    # 描述User模型上用作唯一标识符的字段名称
    # 字段必须必须是唯一的（即在其定义中设置unique=True）
    USERNAME_FIELD = 'id'

    # 当通过createsuperuser管理命令创建一个用户时
    # 系统会提示用户输入以下字段
    REQUIRED_FIELDS = ['username', 'password']

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username

    def __str__(self):
        return self.username

    # def has_perm(self, perm, obj=None):
    #     "Does the user have a specific permission?"
    #     # Simplest possible answer: Yes, always
    #     return True
    #
    # def has_module_perms(self, app_label):
    #     "Does the user have permissions to view the app `app_label`?"
    #     # Simplest possible answer: Yes, always
    #     return True

    @property
    def is_staff(self):
        # "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin

    class Meta:
        db_table = 'user'


class Classify(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='分类ID')
    classify_name = models.CharField(max_length=10, unique=True, verbose_name='分类名')
    admin = models.ForeignKey('User', related_name='classifies', on_delete=models.CASCADE, verbose_name='创建的管理员')

    class Meta:
        db_table = 'classify'


class Tag(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='标签ID')
    tag_name = models.CharField(max_length=10, verbose_name='标签名')
    user = models.ForeignKey('User', related_name='tags', on_delete=models.CASCADE, verbose_name='标签所属用户')

    class Meta:
        db_table = 'tag'


class Fans(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='粉丝表ID')
    user = models.ForeignKey('User', related_name='attentions', on_delete=models.CASCADE, verbose_name='用户')
    attention_user = models.ForeignKey('User', related_name='by_attention', on_delete=models.CASCADE, verbose_name='被关注的用户')
    attention_date = models.DateTimeField(auto_now=True, verbose_name='关注时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否已经取消关注')

    class Meta:
        db_table = 'fans'


class Collect(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='收藏表ID')
    user = models.ForeignKey('User', related_name='collects', on_delete=models.CASCADE, verbose_name='用户')
    article = models.ForeignKey('article.Article', related_name='by_collect', on_delete=models.CASCADE,
                                verbose_name='文章')
    collect_date = models.DateTimeField(auto_now=True, verbose_name='收藏时间')
    is_delete = models.BooleanField(default=False, verbose_name='是否已经取消收藏')

    class Meta:
        db_table = 'collect'


class Avatar(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='头像ID')
    user = models.OneToOneField('User', on_delete=models.CASCADE, related_name='avatar_url', unique=True,
                                verbose_name='用户')
    avatar_url = models.URLField(verbose_name='头像链接')

    class Meta:
        db_table = 'avatar'
